package com.icesoft.core.common.helper.uid.impl;

import com.icesoft.core.common.helper.uid.SnowflakeIdWorker;
import com.icesoft.core.common.helper.uid.UidGenerate;
import com.icesoft.core.common.helper.uid.WorkIdDTO;
import com.icesoft.core.common.util.IdUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SingleUidGenerateImpl implements UidGenerate {
    private volatile WorkIdDTO workIdDTO = new WorkIdDTO(IdUtil.getServerIdAsLong(), 0);

    @Override
    public long nextId() {
        return SnowflakeIdWorker.nextId(workIdDTO, this::convertTimestamp);
    }

    private long convertTimestamp(long timestamp) {
        long sub = SnowflakeIdWorker.getLastTimestamp() - timestamp;
        log.warn("时钟发生了回拨，回拨量：【{}ms】", sub);
        if (sub < 1000) {
            timestamp = SnowflakeIdWorker.getLastTimestamp();
        } else {
            if (workIdDTO.getDatacenterId() < SnowflakeIdWorker.MAX_DATA_CENTER_ID) {
                workIdDTO.setDatacenterId(workIdDTO.getDatacenterId() + 1);
            } else {
                workIdDTO.setWorkerId(workIdDTO.getWorkerId() + 1);
                if (workIdDTO.getWorkerId() > SnowflakeIdWorker.MAX_WORK_ID) {
                    workIdDTO.setWorkerId(0);
                    workIdDTO.setDatacenterId(0);
                }
            }
        }
		return timestamp;
    }

}
